package com.three.crm.http;

import android.os.Environment;

import java.io.File;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Cache;
import okhttp3.OkHttpClient;

/**
 * Created by lqd on 2022-06-15.
 */
public class OkHttpClientUtil {
    private static OkHttpClient singleton;
    //非常有必要，要不此类还是可以被new，但是无法避免反射，好恶心
    private OkHttpClientUtil(){}
    public static OkHttpClient getInstance() {
        if (singleton == null)
        {
            synchronized (OkHttpClientUtil.class)
            {
                if (singleton == null)
                {
                    File sdcache = new File(Environment.getExternalStorageDirectory(),
                            "cache");
                    //指定缓存大小
                    int cacheSize = 10 * 1024 * 1024;
                    //设置超时时间及缓存
                    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                            .connectTimeout(40, TimeUnit.SECONDS)
                            .writeTimeout(40, TimeUnit.SECONDS)
                            .readTimeout(40, TimeUnit.SECONDS)
                            .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
                    singleton = builder.build();
                }
            }
        }
        return singleton;
    }

    public synchronized static OkHttpClient getClient(){
        OkHttpClient okHttpClient = null;
        if (okHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            try {
                // 自定义一个信任所有证书的TrustManager，添加SSLSocketFactory的时候要用到
                final X509TrustManager trustAllCert =
                        new X509TrustManager() {

                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            }

                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            }

                            @Override
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return new java.security.cert.X509Certificate[]{};
                            }
                        };
                final SSLSocketFactory sslSocketFactory = new SSLSocketFactoryCompat(trustAllCert);
                builder.sslSocketFactory(sslSocketFactory, trustAllCert);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            okHttpClient = builder.build();
        }
        return okHttpClient;
    }
}
